package com.heima.file.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.heima.file.common.enums.AppHttpCodeEnum;
import com.heima.file.common.enums.FileType;
import com.heima.file.common.result.ResponseResult;
import com.heima.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/file")
public class FileController {
    @Autowired
    FileService fileService;
    /**
     * 上传文件至OSS     返回文件地址全路径
     */
    @SentinelResource("uploadToOSS")
    @PostMapping("uploadToOSS")
    public ResponseResult<String> uploadToOSS(MultipartFile file){
        try {
            String path = fileService.uploadFile(file, FileType.OSS);
            return ResponseResult.okResult(path);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
    }
    /**
     * 根据路径删除OSS中文件
     */
    @GetMapping("deleteFromOSS")
    public ResponseResult<Boolean> deleteFromOSS(String url){
        try {
            fileService.deleteFile(url,FileType.OSS);
            return ResponseResult.okResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }
    }
    /**
     * 上传html至MINIO   返回静态页地址全路径
     */
    @PostMapping("uploadToMinio")
    public ResponseResult<String> uploadToMinio(MultipartFile file){
        try {
            String path = fileService.uploadFile(file, FileType.MINIO);
            return ResponseResult.okResult(path);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
    }
    /**
     * 根据路径删除minio中文件
     */
    @GetMapping("deleteFromMinio")
    public ResponseResult<Boolean> deleteFromMinIO(String url){
        try {
            fileService.deleteFile(url,FileType.MINIO);
            return ResponseResult.okResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }
    }
}
